package com.backwaveweibo.bww.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author GHW : RD-Kelsey
 * @description 七牛云文件上传工具类
 * @date 2020/6/8
 */
@Slf4j
public class FileUploadWithQiNiuYun {

    //生成上传凭证，然后准备上传
    private static final String ACCESS_KEY = "OeZ3mKc0cwT2RVq-i6tmtmPj55xOp1NdT_6U4NHU";
    private static final String SECRET_KEY = "NG3slWtnHU_lFhI7FimGzfF_hke9LTq9yHDn7OFV";
    private static final String BUCKET_NAME = "back-wave-weibo";
    public static final String DOMAIN = "http://qblnbfo74.bkt.clouddn.com/";
    //七牛云密钥
    private static final Auth AUTH = Auth.create(ACCESS_KEY, SECRET_KEY);

    /**
     * 上传图片到七牛云
     *
     * @param inputStream 输入流
     * @param key         文件名
     * @return 返回文件的七牛云外链 链接
     * @throws QiniuException 文件上传异常
     */
    public static String uploadQNImg(InputStream inputStream, String key) throws QiniuException {
        //华南
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        //原文件名前套一个UUID前缀防止重复
        key = UUID.randomUUID() + key;
        String upToken = AUTH.uploadToken(BUCKET_NAME);
        Response response = uploadManager.put(inputStream, key, upToken, null, null);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.info("七牛云返回的key==>{}" + putRet.key);
        log.info("七牛云返回的hash==>{}" + putRet.hash);
        return DOMAIN + key;
    }

    /**
     * 从七牛云中删除图片
     *
     * @param key 文件名
     */
    public static void delFromQiNiu(String key) throws QiniuException {
        Configuration cfg = new Configuration(Region.region2());
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        bucketManager.delete(BUCKET_NAME, key);
        log.info("已删除七牛云对应的图片 ==> [ " + key + " ]");
    }
}
